package dao

import models.Tables._
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import slick.jdbc.JdbcProfile

import javax.inject.Inject
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

/** Created by yz on 2018/4/17
  */
class DataDao @Inject() (protected val dbConfigProvider: DatabaseConfigProvider)
    extends HasDatabaseConfigProvider[JdbcProfile] {

  import profile.api._

  type MyRow = DataRow
  val table = Data

  def insert(row: MyRow): Future[Unit] = db.run(table += row).map(_ => ())

  def insertAll(rows: List[MyRow]): Future[Unit] = db.run(table ++= rows).map(_ => ())

  def deleteAll = db.run(table.delete)

  def selectAll = db.run(table.result)

  def selectAllRsNumber = db.run(table.map(_.snpNumber).distinct.result).map(_.toList)

  def selectUniqueValues(keys: List[String]) = {
    val action = DBIO.sequence {
      val rs = keys.map { key =>
        table
          .map { t =>
            key match {
              case "nutrient" => t.nutrient
            }
          }
          .distinct
          .result
      }
      rs
    }
    db.run(action)
  }

  def select(rsNumber: String) = db.run(table.filter(_.snpNumber === rsNumber).result.head)

  def selectOp(rsNumber: String) = db.run(table.filter(_.snpNumber === rsNumber).result.headOption)

  def selectById(id: String) = db.run(table.filter(_.id === id).result.head)

}
